<#import "/common/Util.ftl" as Util>
package ${Util.parsePkg(model.handlerClass)};

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.ResourceUploadService;
import ${model.mainPkg}.bizmoduler.system.WcmGeneralGroup8ContentManage;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.controller.core.FileUploadHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.ListUtil;

public class ${Util.parseClass(model.handlerClass)} extends FileUploadHandler{
	private static final String ResourceGroupId = "CF35D1E6-102E-428A-B39C-0072D491D5B1";
	
	public ${Util.parseClass(model.handlerClass)}(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		String grpId = ResourceGroupId;
		WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
		DataParam queryParam = new DataParam("GRP_ID",grpId);
		DataRow row = resourseManage.queryTreeRecord(queryParam);
		String resTypeDesc = row.stringValue("GRP_RES_TYPE_DESC");
		String resTypeExts = row.stringValue("GRP_RES_TYPE_EXTS");
		String resSizeLimit= row.stringValue("GRP_RES_SIZE_LIMIT");

		this.setAttribute("${model.bizIdField}", param.get("${model.bizIdField}"));
		this.setAttribute("GRP_ID", grpId);
		this.setAttribute("GRP_RES_TYPE_DESC", resTypeDesc);
		this.setAttribute("GRP_RES_TYPE_EXTS", resTypeExts);
		this.setAttribute("GRP_RES_SIZE_LIMIT", resSizeLimit);
		return new LocalRenderer(getPage());
	}
	
	@SuppressWarnings("rawtypes")
	@PageAction
	public ViewRenderer uploadFile(DataParam param){
		String responseText = FAIL;
		try {
			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload fileFileUpload = new ServletFileUpload(fac);
			fileFileUpload.setHeaderEncoding("utf-8");
			List fileList = null;
			fileList = fileFileUpload.parseRequest(request);

			Iterator it = fileList.iterator();
			String name = "";
			String fileFullPath = null;
			File filePath = this.buildResourseSavePath(ResourceGroupId);
			
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (item.isFormField()){
					String fieldName = item.getFieldName();
					if (fieldName.equals("${model.bizIdField}")){
						String bizId = item.getString();
						resourceParam.put("${model.bizIdField}",bizId);
					}
					continue;
				}
				name = item.getName();
				resourceParam.put("GRP_ID",ResourceGroupId);
				resourceParam.put("RES_NAME",name);
				String location = resourceRelativePath + "/" + name;
				resourceParam.put("RES_LOCATION",location);
				fileFullPath = filePath.getAbsolutePath()+File.separator+name;
				long resourceSize = item.getSize();
				resourceParam.put("RES_SIZE",String.valueOf(resourceSize));
				String suffix = name.substring(name.lastIndexOf("."));
				resourceParam.put("RES_SUFFIX",suffix);
				resourceParam.put("RES_SHAREABLE","Y");
				
				File tempFile = new File(fileFullPath);
				if (!tempFile.getParentFile().exists()){
					tempFile.getParentFile().mkdirs();
				}
				item.write(tempFile);
				this.insertResourceRecord();
			}
			responseText = SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer delResource(DataParam param){
		String responseText = FAIL;
		try {
			String refId = param.get("${model.primaryKey}");
			ResourceUploadService resourceUploadService = getResourceUploadService();
			List<String> refIdList = new ArrayList<String>();
			String[] refIds = refId.split(",");
			ListUtil.addArrayToList(refIdList, refIds);
			resourceUploadService.deleteResourceRelations(refIdList);
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer loadResourceList(DataParam param){
		String responseText = FAIL;
		String bizId = param.get("${model.bizIdField}");
		try {
			ResourceUploadService resourceUploadService = getResourceUploadService();
			DataParam queyrParam = new DataParam("${model.bizIdField}",bizId);
			List<DataRow> records = resourceUploadService.findResourceRelations(queyrParam);
			if (records != null && records.size() > 0){
				JSONArray jsonArray = new JSONArray();
				for (int i=0;i < records.size();i++){
					JSONObject jsonObject = new JSONObject();
					DataRow row = records.get(i);
					String dataText = row.stringValue("RES_NAME");
					String dataValue = row.stringValue("${model.primaryKey}");
					jsonObject.put("text", dataText);
					jsonObject.put("value",dataValue);
					jsonArray.put(jsonObject);	
				}
				responseText = jsonArray.toString();
			}			
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
	
	private void insertResourceRecord(){
		WcmGeneralGroup8ContentManage resourseManage = this.lookupService(WcmGeneralGroup8ContentManage.class);
		resourseManage.createtContentRecord("WcmGeneralResource", resourceParam);
		String resId = resourceParam.get("RES_ID");
		String bizId = resourceParam.get("${model.bizIdField}");
		ResourceUploadService resourceUploadService = getResourceUploadService();
		resourceUploadService.createResourceRelation(bizId, resId);
	}
	
	private ResourceUploadService getResourceUploadService(){
		return (ResourceUploadService)this.lookupService("${Util.parseClass(model.resFileServiceId)}");
	}
}